<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\OrderModel;
use Utuo\PHPExcel;
use My\Model\DistributionShopRateModel;

class DistributionShopAgentStockGoodsController extends BackgroundController {
    
    private $deliverMethod = array(
        '0' => '物流',
        '1' => '无需配送',
    );
    
    /* 订单类型 */
    protected $orderTypes = array(
        0 => '待发货',
        1 => '交易成功',
        3 => '待买家签收',
        4 => '待卖家审核评价',
        5 => '待买家付款',
        7 => '已支付订单',
        6 => '退款订单',
        2 => '全部',
    );
    
    public function _initialize() {
        $this->setControllerTitle("代理进货管理");
		$this->setActionTitle(array(
			'index' => '订单列表',
			'deliver' => '发货',
			'detials' => '订单详细',
		));
        $this->setActionNav('index');
    }
    
    /**
     * 获得查询参数
     * @return $params
     * array(
     * 	 'agentId', // 代理id*
     * 	 'type' // 类型 *
     * 	 'tel' // 收货人电话
     * 	 'consignee' // 收货人
     * 	 'orderId' // 订单id
     * )
     */
    private function getParams() {
        $agentId = I('agentId', -1, "intval"); // 发货代理id  0.厂家   -1.全部
        $type = I("type", 0);  // 查询类型
        $consignee = I("consignee"); // 收货人
        $openId = I("openId");  // 收货人openId
        $orderId = I("orderId"); // 订单id
        $tel = I("tel");  // 收货人电话
        $params = array();
    
        /* 订单id */
        if ( !empty($orderId) ) {
            $params['orderId'] = $orderId;
        }
    
        /* 代理id(*)  */
        if ( $agentId*1 > 0 ) {
            $agent = M("Agent")->where("id=%d", $agentId)->find();
            if ( !$agent ) {
                $agentId = -1;
            }
        } elseif ( $agentId*1 === -1 ) {
            // 全部
        } elseif ( $agentId*1 === 0 ) {
            // 总商家
        } else {
            $agentId = -1;
        }
        $params['agentId'] = $agentId;
    
        /* 类型(*) */
        if ( !in_array( $type, array_keys( $this->orderTypes ) ) ) {
            $type = 2;
        }
        $params['type'] = $type;
    
        /* 收货人电话  */
        if ( !empty($tel) ) {
            $params['tel'] = $tel;
        }
    
        /* 收货人  */
        if ( !empty($consignee) ) {
            $params['consignee'] = $consignee;
        }
    
        /* 收货人  */
        if ( !empty($openId) ) {
            $params['openId'] = $openId;
        }
    
        return $params;
    }
    
    /**
     * 获得参数与查询条件
     */
    private function getCondition( $params ) {
        $agentId = $params['agentId']; // 发货代理id  0.厂家   -1.全部
        $type = $params['type']; // 查询类型
        $consignee = $params['consignee']; // 收货人
        $orderId = $params['orderId']; // 订单id
        $tel = $params['tel']; // 收货人电话
        $openId = $params['openId']; // 收货人openId
    
        $condition = array( 'orders.cid' => $this->aid, 'orders.is_deleted' => 0);
    
        /** 筛选条件 */
        if ( !empty($orderId) ) {
            $condition['orders.order_no'] = $orderId;
        }
    
        if ( $agentId*1 >= 0 ) {
            $condition['orders.agent_id'] = $agentId;
        }
    
        /* 类型 */
        if( $type == 0 ) { // 待发货
            $condition['orders.order_status'] = OrderModel::ORDER_STATUS_SHIPPING;
        } elseif ($type == 1) { // 交易成功
            $condition ['orders.order_status'] = OrderModel::ORDER_STATUS_COMPLETED;
        } elseif($type == 3) { // 待买家签收
            $condition ['orders.order_status'] = OrderModel::ORDER_STATUS_SIGN;
        } elseif($type == 4) { // 待卖家完成评价
            $condition ['orders.order_status'] = OrderModel::ORDER_STATUS_COMPLETED;
            $condition ['orders.rate_status'] = array('in', array(DistributionShopRateModel::RATE_STATUS_BUYER)) ;
        } elseif($type == 5) { // 待买家付款
            $condition ['orders.order_status'] = OrderModel::ORDER_STATUS_PAY;
            $condition ['orders.pay_status'] = OrderModel::PAY_STATUS_NOT_PAID;
        } elseif($type == 6) {
            $condition['orders.refund_status'] = array('in', array(
                OrderModel::ORDER_REFUND_STATUS_ON,
                OrderModel::ORDER_REFUND_STATUS_FINISH,
            ),
            );
        } elseif($type == 7) {
            $condition ['orders.pay_status'] = OrderModel::PAY_STATUS_PAID;
            $condition ['orders.refund_status'] = 0; // 非退款订单
        }
    
        /* 收货人电话  */
        if ( !empty($tel) ) {
            $condition['orders.tel'] = $tel;
        }
    
        /* 收货人  */
        if ( !empty($consignee) ) {
            $condition['orders.consignee'] = array('like', "%{$consignee}%");
        }
    
        /* openId  */
        if ( !empty($openId) ) {
            $condition['user.openId'] = array('eq', "{$openId}");
        }
    
        return $condition;
    }
    
    /**
     * 订单列表
     */
    public function indexAction() {
        $belongs = array(
            '-1' => '全部',
            '0' => '总商家',
        );
        $this->setActionLink();
        $dso = D("Order");
        $d = D("Order orders");
        $params = $this->getParams();
        $condition = $this->getCondition($params);
        /* 查询  */
        $orderLists = $d->join("__WECHAT_USER__ user on user.id=orders.uid")->where($condition)->field("orders.*,user.nickname,user.openId")->limit($this->getPageSize())->page($this->getPage())->order("id desc")->select();
        $productOrderCount = $d->where($condition)->count();
        $this->bindOrderDetail ( $orderLists );
        if ( $params['agentId']*1 > 0 ) {
            $agent = M("Agent")->where("id=%d", $params['agentId'])->find() and $belongs[$agent['id']] = $agent['name'];
        }
        $this->assign("belongsOptions", $this->getOption($belongs, $params['agentId']));
        $this->assign("orderTypesOptions", $this->getOption($this->orderTypes, $params['type']));
        $this->assign("params", $params);
        $this->showPage($productOrderCount, $this->getPageSize(), $params);
        $this->assign("productOrderLists", $orderLists);
        $this->display();
    }
    
    /**
     * 导出Excel
     */
    public function exportXLSAction() {
        $type = I('type', 0, 'intval');
        $startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
        $endDate = I('endDate', 0, 'intval') or $endDate = time();
        $params = array(
            'type' => $type,
            'startDate' => $startDate,
            'endDate' => $endDate,
        );
        $productOrderGoodsLists = $this->search( $params );
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("微美风铃")
                    ->setLastModifiedBy("微美风铃")
                    ->setTitle("销售报表")
                    ->setSubject("销售报表")
                    ->setDescription("销售报表")
                    ->setKeywords("销售 报表")
                    ->setCategory("报表");
    
    
        /*设置标题*/
        $titles = array('订单编号','商品总计','订单运费','订单合计','收件人','地址','电话','下单时间','产品名称','数量','拍下价格','规格');
        $fields = array('order_no'=> array('type'=>'string'),
                        'goods_amount'=> array('type'=>'string'),
                        'shipping_fee' => array('type'=>'string'),
                        'total' => array('type'=>'string'),
                        'consignee' => array('type'=>'string'),
                        'fullAddress' => array('type'=>'string'),
                        'tel' => array('type'=>'string'),
                        'create_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
                        'goods_name' => array('type'=>'string'),
                        'goods_number' => array('type'=>'string'),
                        'goods_price' => array('type'=>'string'),
                        'goods_attr' => array('type'=>'string'));
        $sheet0 = $objPHPExcel->setActiveSheetIndex(0);
        $rowNumber = 1;
        foreach ($titles as $k => $v) {
            $sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
        }
        $rowNumber++;
        foreach ( $productOrderGoodsLists as $v ) {
            $fieldIndex = 0;
            foreach ( $fields as $k0 => $v0 ) {
                $cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
                $sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
                //$sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
            }
            $rowNumber++;
        }
        $objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1'); // IE9时
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
    
    
    /**
     * 导出
     */
    public function exportOrderXLSAction() {
        $type = I('type', 0, 'intval');
        $startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
        $endDate = I('endDate', 0, 'intval') or $endDate = time();
        $params = array(
            'type' => $type,
            'startDate' => $startDate,
            'endDate' => $endDate,
        );
        $productOrderGoodsLists = $this->search( $params, false );
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("微美风铃")
                    ->setLastModifiedBy("微美风铃")
                    ->setTitle("销售报表")
                    ->setSubject("销售报表")
                    ->setDescription("销售报表")
                    ->setKeywords("销售 报表")
                    ->setCategory("报表");
    
    
        /*设置标题*/
        $titles = array('订单编号','商品总计','订单运费','订单合计','收件人','地址','电话','下单时间','订单状态');
        $fields = array('order_no'=> array('type'=>'string'),
                        'goods_amount'=> array('type'=>'string'),
                        'shipping_fee' => array('type'=>'string'),
                        'total' => array('type'=>'string'),
                        'consignee' => array('type'=>'string'),
                        'fullAddress' => array('type'=>'string'),
                        'tel' => array('type'=>'string'),
                        'create_time'=>array('type'=>'datetime', 'format' => 'Y/m/d H:i:s'),
                        'orderStatusName' => array('type'=>'string'),);
        $sheet0 = $objPHPExcel->setActiveSheetIndex(0);
        $rowNumber = 1;
        foreach ($titles as $k => $v) {
            $sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
        }
        $rowNumber++;
        foreach ( $productOrderGoodsLists as $v ) {
            $fieldIndex = 0;
            foreach ( $fields as $k0 => $v0 ) {
                $cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
                $sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
                //$sheet0->setCellValue(chr(ord('A')+$fieldIndex++).$rowNumber, $this->getShowData($v[$k0], $v0));
            }
            $rowNumber++;
        }
        $objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1'); // IE9时
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
    
    /**
     * 查询
     * @param array $params 查询条件
     * @param bool 是否显示详细
     * @return Ambigous <\Think\mixed, string, boolean, NULL, multitype:, mixed, object>
     */
    private function search( $params, $detail = true ) {
        $params = $this->getParams();
        $condition = $this->getCondition($params);
        $fields = "orders.*, concat(province.name,' ',city.name,' ', area.name,' ',orders.address) as fullAddress,
                   extends.user_type,extends.agent_recommend_tree,extends.agent_layer_tree,extends.settle_status,extends.reward_uids,extends.reward_bonus,extends.reward_uids_recommend,extends.reward_bonus_recommend";
        $orders = D("Order orders");
        $result =$orders->join( "__ORDER_PACKAGE_EXTEND__ extends on orders.id=extends.order_id", "LEFT" )
                        ->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
                        ->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
                        ->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
                        ->where( $condition );
    	if ( $detail ) {
			$orders->join('__ORDER_GOODS__ goods on orders.id=goods.order_id');
			$fields.=",goods.goods_name,goods.goods_number,goods.goods_price,goods.goods_attr";
		}
		$result = $orders->field( $fields )->select();
        foreach ( $result as $k => &$v ) {
            $v['orderStatusName'] = $this->getOrderShowStatus ( $v );
        }
        return $result;
    }
    
    // 发货
    public function deliverAction() {
        $d = D("Order");
        $orderId = I("id", 0);
        $productOrder = $d->where(array(
            'cid' => $this->aid,
            'id' => $orderId,
        ))->find();
        $this->assign("productOrder", $productOrder);
        $this->display();
    }
    
    // 发货提交
    public function deliverPostAction() {
        $d = D("Order");
        $orderId = I("id", 0, "intval");
        // 验证
        $order = $d->where(array( "cid" => $this->aid, "id" => $orderId))->find();
        $order or $this->ajaxError("订单不存在");
        $order['order_status'] == OrderModel::ORDER_STATUS_SIGN and $this->ajaxError("订单已发货");
        $d->field('deliver_method,express_name,shipping_no,deliverman_uid')->create();
        $data = array(
            'order_status' => OrderModel::ORDER_STATUS_SIGN,
            'shipping_time' => time(),
            'expect_take_time' => time() + 7 * 24 * 3600,
        );
        if( $d->deliver_method == 0 ) {
            $data['express_name'] = $d->express_name or $this->ajaxError("请选择快递名称.");
            $data['shipping_no'] = $d->shipping_no or $this->ajaxError("请填写物流单号.");
        } elseif( $d->deliver_method == 1 ) {
            // 无需配送
        } else {
            $this->ajaxError("没有您选择的配送方式");
        }
        $data['deliver_method'] = $d->deliver_method;
        // 更新产品销量
        $productSalesSummary = M("OrderGoods")->where(array(
                                    "order_id" => $orderId
                                ))->group("goods_id")->field("goods_id,sum(goods_number) as totalName")->select();
        foreach ($productSalesSummary as $v) {
            M("DistributionShopPackage")->where("id=%d", $v['goods_id'])->setInc("saled_count", 1);
        }
        // 设置发货状态
        false !== $d->where(array( 'id' => $orderId, ))->save($data) and $this->ajaxSuccess("发货成功");
        $this->ajaxSuccess("发货失败");
    }
    
    /**
     * 订单详细
     */
    public function detialsAction() {
        $orderId = I("id", 0);
        $order = $this->getOrder($orderId);
        if ( in_array('deliver', $order['operates']) ) {
            $express = \Utuo\Express::getInstance();
            $expressNames = $express->getExpressname();
            $expressValues = array_values($expressNames);
            $order['deliverMethodRadio'] = $this->getRadio("deliver_method", $this->deliverMethod, '0');
            $order['expressOptions'] = $this->getOption(array_combine($expressValues, $expressValues), $order['express_name'], "====请选择快递====");
        }
        $this->assign("order", $order);
        $this->display();
    }
    
    private function setActionLink() {
        foreach ($this->orderTypes as $k => $v) {
            $this->setLinkNav("$v", U('DistributionShopAgentStockGoods/index', array('type'=>$k)));
        }
    }
    
    // 获得订单操作
    private function getOperate( &$v ) {
       $operates = array();
       
       if( $v['order_status'] == OrderModel::ORDER_STATUS_SHIPPING ) {
            $operates[] = "deliver";
       }
       
       $v['operates'] = $operates;
    }
    
    /**
     * 获得一个订单
     * @param unknown $id
     * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string, object>
     */
    private function getOrder( $id ) {
        $order = M ( "Order orders" )->join( "__ORDER_PACKAGE_EXTEND__ extends on orders.id=extends.order_id", "LEFT"  )
                                    ->join( "__WECHAT_USER__ user on orders.uid=user.id", "LEFT")
                                    ->join( "__AGENT__ agent on agent.id = orders.agent_id", "LEFT" )
                                    ->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
                                    ->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
                                    ->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
                                    ->field ( "orders.*,
                                               extends.user_type,extends.agent_recommend_tree,extends.agent_layer_tree,extends.settle_status,extends.reward_uids,extends.reward_bonus,extends.reward_uids_recommend,extends.reward_bonus_recommend,
                                               user.nickname as userName,
                                               province.name as provinceName, city.name as cityName, area.name as areaName, agent.name as agentName" )
                                    ->where ( "orders.id=%d", $id )->find ();
        if ( !$order ) return null;
        $orders = array (
            &$order
        );
        $this->bindOrderDetail ( $orders );
        return $order;
    }
    
    /* 绑定订单详细 */
    private function bindOrderDetail(&$orderLists) {
        /* 关联订单商品 */
        foreach ( $orderLists as &$v ) {
            // 绑定显示状态
            $v ["orderStatusName"] = $this->getOrderShowStatus ( $v );
            // 订单佣金信息
            $rewardUids = $v['reward_uids'];
            $rewardBonus  = $v['reward_bonus'];
            $rewardUidsRecommend  = $v['reward_uids_recommend'];
            $rewardBonusRecommend  = $v['reward_bonus_recommend'];
            $totalBouns = array();
            if ( $rewardUids ) {
                $newArray = array_combine(explode(',', $rewardUids), explode(',', $rewardBonus));
                foreach ( $newArray as $uid => $bouns ) {
                    $totalBouns[$uid]['bonus']+=$bouns;
                }
            }  
            if ( $rewardUidsRecommend ) {
                $newArray = array_combine(explode(',', $rewardUidsRecommend), explode(',', $rewardBonusRecommend));
                foreach ( $newArray as $uid => $bouns ) {
                    $totalBouns[$uid]['bonusRecommend']+=$bouns;
                }
            }    
            if ( $totalBouns ) {
                $bonusUserIds = array_keys($totalBouns);
                $bonusUsers = M("Agent agent")->join("__WECHAT_USER__ user on agent.wechat_uid=user.id", "LEFT")->where(array('agent.id' => array("in", $bonusUserIds)))->getField("agent.id,agent.level,user.nickname,user.face,user.openId");
                $v['bonusInfo'] = $totalBouns;
                $v['bonusUser'] = $bonusUsers;
            }
            // 获得操作
            $this->getOperate($v);
            // 绑定订单商品
            $orderGoods = M ( "OrderGoods goods" )->join("__ORDER_PACKAGE_ITEMS__ items on goods.id=items.order_goods_id", "LEFT")->where ( "goods.order_id=%d", $v ['id'] )->select ();
            foreach ( $orderGoods as &$v0 ) {
                $v ['items'] [$v0 ['goods_id']] or $v ['items'] [$v0 ['goods_id']] = array (
                    'goods_id' => $v0 ['goods_id'],
                    'goods_name' => $v0 ['goods_name'],
                    'items' => array ()
                );
                $v ['items'] [$v0 ['goods_id']] ['items'] [] = array (
                    'goods_pic' => $v0 ['goods_pic'],
                    'goods_number' => $v0 ['goods_number'],
                    'goods_price' => $v0 ['goods_price'],
                    'goods_attr' => $v0 ['goods_attr']
                );
            }
        }
    }
    
    /**
     * 获得订单显示状态
     * @param $status 订单状态
     * @param $payStatus 支付状态
     */
    public function getOrderShowStatus( $order ) {
        $status = $order['order_status'];
        $payStatus = $order['pay_status'];
        $statusText = "";
        if(isset(OrderModel::$ORDER_STATUS[$status])) {
            if(!$payStatus and ($status == OrderModel::ORDER_STATUS_SHIPPING or $status == OrderModel::ORDER_STATUS_SIGN)) {
                $statusText = OrderModel::$ORDER_STATUS[$status]."(货到付款)";
            } else {
                $statusText =  OrderModel::$ORDER_STATUS[$status];
            }
        } else {
            $statusText = OrderModel::$ORDER_STATUS[0];
        }
        return $statusText;
    }
    
    /**
     * 获得单元格格式
     * @param unknown $fieldCfg
     * @return string
     */
    private function getCellFormat( $fieldCfg ) {
        if( $fieldCfg['type'] == 'string' ) {
            return \PHPExcel_Cell_DataType::TYPE_STRING;
        }
        return \PHPExcel_Cell_DataType::TYPE_STRING;
    }
    
    /**
     * 获得数据展示格式
     * @param unknown $value
     * @param unknown $fieldCfg
     * @return string|unknown
     */
    private function getShowData($value, $fieldCfg) {
        if( $fieldCfg['type'] == 'datetime' ) {
            return date( $fieldCfg['format'], $value);
        }
        return $value;
    }
    
}